// get_post_comments_by_keyword
// get_post_list_by_keyword
const getPostByKeyword = {
    raseData: {},
    taskConfig: { taskStatus: false },
    viewPostList: [],
    postList: {
        collect_id: '',
        post: []
    },
    tipContent:{ get_post_list_by_keyword: '关键词采集笔记列表', get_post_comments_by_keyword: '关键字采集评论用户' },
    initOtherData() {
        getPostByKeyword.viewPostList = []
    },
    watchValue(key, newVal) {

        if (key == 'taskStatus' && newVal) {
            console.log('postList', JSON.stringify(getPostByKeyword.postList));
            Xhs.taskConfig.taskStatus = true
        }

        if (key == 'errorTask' && newVal) {
            let skey = getPostByKeyword.raseData.skey
            if (newVal) {
                // 所有任务数据均执行异常
                let params = {
                    taskType: skey,
                    task_id: getPostByKeyword.raseData.task_id,
                    taskName: getPostByKeyword.tipContent[skey],
                    taskData: getPostByKeyword.raseData,
                    errorTip: newVal,
                    taskDate: Comman.getDate()
                }
                Xhs.errorTask(params)
                getPostByKeyword.taskConfig.taskStatus = true
            }
        }
    },
    init(data) {
        getPostByKeyword.postList = {
            collect_id: data.setting.collect_id || '',
            post: []
        }
        getPostByKeyword.raseData = data;
        getPostByKeyword.taskConfig = Comman.defineReactive(
            {
                taskStatus: false,
                errorTask: '',
            },
            '',
            getPostByKeyword.watchValue
        )
        getPostByKeyword.initOtherData()
        getPostByKeyword.openTask()
    },
    start(data) {
        //初始化数据
        getPostByKeyword.init(data)
    },
    openTask() {
        let setting = getPostByKeyword.raseData.setting
        let homeMnue = btnConfig.home.homeMnue
        let homeBtn = btnConfig.home.homeBtn
        let searchIconBtn = btnConfig.home.searchIconBtn
        let searchBtn = btnConfig.search.searchBtn

        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back');
            sleep(2000);
        }
        //点击首页
        let nowHomeBtn = homeBtn.default()
        if (!nowHomeBtn) {
            console.log('首页按钮不存在，请检查并手动复原首页重新启动');
            getPostByKeyword.taskConfig.errorTask = '首页按钮不存在'
            return
        }
        if (nowHomeBtn.bounds) {
            App.clickByBtn(nowHomeBtn, 3)
        } else {
            App.click(homeBtn.position.x, homeBtn.position.y, 3)
        }
        //点击搜索图标按钮
        let nowSearchIconBtn = searchIconBtn.default()
        if (!nowSearchIconBtn) {
            console.log('搜索图片不存在，并手动复原重新启动');
            getPostByKeyword.taskConfig.errorTask = '搜索图片不存在'
            return
        }
        if (nowSearchIconBtn.bounds) {
            App.clickByBtn(nowSearchIconBtn, 3)
        } else {
            App.click(searchIconBtn.position.x, searchIconBtn.position.y, 3)
        }
        //输入关键字搜索
        setText(setting.collect_content)
        sleep(2000)

        //点击搜索按钮
        let nowSearchBtn = searchBtn.default()
        if (!nowSearchBtn) {
            console.log('搜索按钮不存在，请检查并手动复原重新启动');
            getPostByKeyword.taskConfig.errorTask = '搜索按钮不存在'
            return
        }
        if (nowSearchBtn.bounds) {
            App.clickByBtn(nowSearchBtn, 3)
        } else {
            App.click(searchBtn.position.x, searchBtn.position.y, 3)
        }
        let tip = id('bim').findOne(2000)
        if (tip) {
            console.log('存在提示，点击关闭')
            App.clickByBtn(tip, 3)
        }
        //开启自动浏览任务
        getPostByKeyword.startTask(setting)
    },
    startTask(setting) {
        let data =  getPostByKeyword.raseData
        let endTime = data.time[1] * 1000
        let nowTimeTask = new Date().getTime()
        console.log('任务结束日期：', new Date(endTime).toLocaleDateString() + new Date(endTime).toLocaleTimeString());
        sleep(2000)
        let endNum = setting.num * 1 || 0
        let nowPost = getPostByKeyword.postList.post.length || 0
        if (getPostByKeyword.taskConfig.taskStatus) {
            return
        }
        if (endNum <= nowPost || endTime <= nowTimeTask) {
            //任务已结束
            console.log(endTime <= nowTimeTask ? '已到任务结束时间' :'采集已完成');
            if (!getPostByKeyword.taskConfig.taskStatus) {
                getPostByKeyword.taskConfig.taskStatus = true
            }
            return;
        }
        let postList = btnConfig.search.postList.default()
        let postBtn = btnConfig.search.postBtn.default()
        console.log('当前已收集：' + nowPost);
        if (!postList) {
            console.log('未找到帖子列表，请检查');
            getPostByKeyword.taskConfig.errorTask = '未找到帖子列表'
            return;
        }
        if (!postBtn.length) {
            console.log('未找到帖子，搜索失败');
            if (!getPostByKeyword.taskConfig.taskStatus) {
                getPostByKeyword.taskConfig.taskStatus = true
            }
            return;
        }
        console.log('页面的所有笔记：', postBtn.length);
        postBtn.forEach((item, index) => {
            let nowTime = new Date().getTime()
            let nowPostLength = getPostByKeyword.postList.post.length || 0
            if (endTime <= nowTime || endNum <= nowPostLength) {
                //任务已结束
                console.log(endTime <= nowTimeTask ? '已到任务结束时间' :'采集已完成');
                if (!getPostByKeyword.taskConfig.taskStatus) {
                    getPostByKeyword.taskConfig.taskStatus = true
                }
                return;
            }
            if (getPostByKeyword.taskConfig.taskStatus) {
                return
            }
            let text = item.findOne(id('g8r'))
            let like = item.findOne(id('dxo'))
            if(!text){
                return
            }
            console.log(index + ' \ 笔记：' + text.text());
            if ((!like || like.text() == '赞') && setting.like_min * 1 > 0) {
                console.log('赞数不满足门槛，跳过此笔记');
                // 不满足赞数门槛
                return
            }

            if (like.text() * 1 >= setting.like_min) {
                console.log('赞数满足门槛');
                if (getPostByKeyword.viewPostList.findIndex(view => view == text.text()) == -1) {
                    //未浏览的笔记
                    getPostByKeyword.viewPostList.push(text.text())
                    getPostByKeyword.resolveItem(item, text.text())
                }
            }
            sleep(1000)
        })
        //遍历后翻页
        if (postList) {
            //翻页新笔记
            let nowPostLg = getPostByKeyword.postList.post.length || 0
            let viewNum = getPostByKeyword.viewPostList.length || 0
            let safteyNum = endNum >= 30 ? 200 :  endNum * 5

            if(viewNum >= safteyNum && endNum > nowPostLg){
                //浏览超出安全浏览量，且任务并未收集完成，则直接退出
                console.log('浏览超出安全浏览量，且任务并未收集完成，则直接退出');
                
                if (!getPostByKeyword.taskConfig.taskStatus) {
                    getPostByKeyword.taskConfig.taskStatus = true
                }
                return
            }

            if (endNum > nowPostLg && postList.scrollable()) {
                console.log('未收集完成 - 翻页');
                postList.scrollForward()
                //翻页新笔记
                getPostByKeyword.startTask(setting)
            } else {
                // 到数量笔记 或 无法滑动列表
                if (!getPostByKeyword.taskConfig.taskStatus) {
                    getPostByKeyword.taskConfig.taskStatus = true
                }
            }
        }
    },
    resolveItem(item, text) {
        App.clickByBtn(item, 3)
        let infoDom = btnConfig.post.contentInfo.default()
        let infoDom2 = btnConfig.post.contentInfo2.default()
        let titleDom = btnConfig.post.titleInfo.default()
        let likeDom = className('android.widget.Button').descContains('点赞').findOne(2000)
        let saveDom = className('android.widget.Button').descContains('收藏').findOne(2000)
        let commentDom = className('android.widget.Button').descContains('评论').findOne(2000)
        let shareBrn = btnConfig.post.shareBrn.default()
        // let userName = btnConfig.post.userName.default() || btnConfig.post.userName2.default()
        let viewComment = []
        let targetSave = (getPostByKeyword.raseData.setting.save_min || 0) * 1
        let targeComment = (getPostByKeyword.raseData.setting.comment_min || 0) * 1
        let targetLike = (getPostByKeyword.raseData.setting.like_min || 0) * 1


        if (commentDom) {
            postInfo = {
                link: "",
                title: titleDom ? titleDom.text() : '',
                content: infoDom ? infoDom.text() : infoDom2 ? infoDom2.desc() : '',
                like_num: likeDom ? likeDom.desc().split('点赞')[1] * 1 : 0,
                save_num: saveDom ? saveDom.desc().split('收藏')[1] * 1 : 0,
                comment_num: commentDom ? commentDom.desc().split('评论')[1] * 1 : 0,
                send_time: '',
                comments: []
            }
            if (postInfo.save_num >= targetSave && postInfo.comment_num >= targeComment && postInfo.like_num >= targetLike) {
                console.log('满足所有条件，处理帖子信息');
                getPostByKeyword.getLinke(shareBrn, postInfo)
                if (getPostByKeyword.raseData.skey == 'get_post_comments_by_keyword') {
                    //收集帖子信息后，还需要收集对应评论
                    if (commentDom.bounds) {
                        App.clickByBtn(commentDom, 3)
                    } else {
                        App.click(btnConfig.post.resolveBtn.position.x, btnConfig.post.resolveBtn.position.y, 3)
                    }
                    let closeBtn = id('b4n').findOne(2000)
                    getPostByKeyword.resolveCommentList(postInfo, viewComment, 1)
                    if (closeBtn) {
                        //留言列表是弹窗形式
                        back()
                        sleep(2000)

                    }
                }
                console.log('帖子信息：', postInfo);
                //关键词收集评论 -  如果没有评论
                if(getPostByKeyword.raseData.skey == 'get_post_comments_by_keyword' && postInfo.comments && postInfo.comments.length){
                    getPostByKeyword.postList.post.push(postInfo)
                }
                if(getPostByKeyword.raseData.skey !== 'get_post_comments_by_keyword' ){
                    getPostByKeyword.postList.post.push(postInfo)
                }
            }
        }
        App.randomSleep(2, 4)
        console.log('resolveItem-back');
        back()
        sleep(2000)
    },
    getLinke(shareBrn, postInfo) {
        if (shareBrn) {
            App.clickByBtn(shareBrn, 3)
            let moreBtnMenu = btnConfig.post.moreBtnMenu.default()
            let copyBtn = btnConfig.post.copyBtn.default()
            if (!moreBtnMenu) {
                console.log('找不到moreBtnMenu');
            }
            if (!copyBtn) {
                let scroll = true
                while (!copyBtn && scroll) {
                    try {
                        scroll = moreBtnMenu.scrollForward()
                        sleep(2000)
                        copyBtn = btnConfig.post.copyBtn.default()
                        sleep(2000)
                    } catch (error) {
                        scroll = false
                    }
                }
                if (!copyBtn) {
                    console.log('找不到复制链接按钮');
                }
            }

            if (copyBtn.bounds) {
                App.clickByBtn(copyBtn, true)
            } else {
                App.click(btnConfig.post.copyBtn.position.x, btnConfig.post.copyBtn.position.y, true)
            }
            // launch(Xhs.AppPackName)
            // sleep(1000)
            // postInfo['link'] = getClip() || ''
            // sleep(3000)
            // launch(Xhs.packName);
            let resolveInputBtn = btnConfig.post.resolveInputBtn.default()
            if (resolveInputBtn) {
                App.clickByBtn(resolveInputBtn, 3)
                let input = btnConfig.post.resolveInput.default() ||  btnConfig.post.resolveInput2.default()
                if (input) {
                    input.paste()
                    App.randomSleep(2, 4)
                    input = btnConfig.post.resolveInput.default() ||  btnConfig.post.resolveInput2.default()
                    postInfo['link'] = input ? input.text() : '查询文章链接失败'
                    setText('')
                    sleep(1000)
                    back()
                }
                sleep(2000)
            } else {
                console.log('找不到输入框');
            }
        } else {
            console.log('找不到分享按钮');
        }
    },
    resolveCommentList(postInfo, viewComment, page) {
        if(page >= Xhs.CommentPage){
            console.log('评论页数超过设定值，停止收集')
            return
        }
        let setting = getPostByKeyword.raseData.setting
        let commentList = btnConfig.post.commentList.default() || btnConfig.post.commentList2.default()
        if (!commentList) {
            console.log('找不到评论列表');
            postInfo.comments = []
            return
        }
        let commentItems = btnConfig.post.commentItem1.default()
        if (!commentItems.length) {
            postInfo.comments = []
            return
        } else {
            console.log('评论列表：', commentItems.length + '\n关键词：' + setting.collect_keyword);
        }
        commentItems.forEach((commentItem) => {
            let text = commentItem.findOne(id('jch'))
            let name = commentItem.findOne(id('jjo'))
            if (!text || !name) {
                return
            }
            console.log('当前浏览评论用户: ' + name.text() + ' 内容: ' + text.text());
            //查询是否浏览过
            let findIndex = viewComment.findIndex((item) => {
                return item == name.text()
            })
            console.log('内容是否匹配---' + (findIndex == -1 && setting.collect_keyword.some((item)=>text.text().includes(item))));

            //未浏览过的用户评论，包含关键字匹配,收集
            if (findIndex == -1 && setting.collect_keyword.some((item)=>text.text().includes(item))) {
                viewComment.push(name.text())
                getPostByKeyword.filterCommant(text.text(), commentItem, postInfo.comments)
            }
            sleep(1000)
        });
        console.log('scrollForward()', commentList.scrollable());
        if (commentList.scrollable()) {
            //可以滑动
            if (commentList.scrollForward()) {
                getPostByKeyword.resolveCommentList(postInfo, viewComment, (page += 1))
            } else {
                console.log('滑动失败，没有更多评论了');
            }
        } else {
            console.log('没有更多评论了');
            //触底了
        }
    },
    filterCommant(commanText, commentItem, commentList) {
        if (commanText.includes('-') || commanText.includes('6天前')) {
            //超时，不涉及
            return
        }
        let imgBtn = commentItem.findOne(id('e98'))
        if (!imgBtn) {
            console.log('找不到图片按钮');
            return
        }
        App.clickByBtn(imgBtn, 3)
        let userNick = btnConfig.user.userPageNick.default()
        let userLocation = btnConfig.user.userPageLocation.default()
        let userId = btnConfig.user.userPageId.default()

        if (userId) {
            let commentInfo = {
                content: commanText,
                xhsid: userId ? userId.text().replace('小红书号：', '') : '',
                nickname: userNick ? userNick.text() : '',
                avatar: "",
                ip: userLocation ? userLocation.text().replace('IP属地：', '') : '',
            }
            console.log('comments', commentInfo);
            commentList.push(commentInfo)
        }
        console.log('filterCommant-back');
        back()
        sleep(2000)
    }
}
module.exports = getPostByKeyword